import 'package:base_plugin/base_plugin.dart';
import 'package:finance_app/generated/a.dart';
import 'package:finance_app/generated/l10n.dart';
import 'package:finance_app/src/common/app_colors.dart';
import 'package:finance_app/src/common/config.dart';
import 'package:finance_app/src/entities/bill_entity.dart';
import 'package:finance_app/src/entities/invoice_entity.dart';
import 'package:finance_app/src/router_gen/router_gen_providers.dart';
import 'package:finance_app/src/utils/permission_utils.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_svg/flutter_svg.dart';
import 'package:flutter_svg/svg.dart';

import 'default_bottom_sheet.dart';

/// 首页面板添加按钮
///
/// onTapValue 当前点击的功能
/// dashTypes 需要展示的分类
showDashboardAddBottomSheet(
  BuildContext context, {
  ValueChanged<String> onTapValue,
  List<DashBoardAddType> dashTypes = DashBoardAddType.values,
  bool isSelectMode = false,
}) =>
    showDefaultBottomSheet(context,
        isScrollControlled: true,
        hasClosed: true,
        topMargin: dashTypes.length == 1 ? 60 : 22,
        bottomMargin: 30,
        child: DashboardAddWidget(
          onTapValue: onTapValue,
          dashTypes: dashTypes,
        ));
enum DashBoardAddType {
  sales,
  purchase,
  other,
  accountTransaction,
  ExpanseOrBill,
  purchaseSummary,
  saleSummary,
  payroll,
}

class DashboardAddWidget extends StatelessWidget {
  final ValueChanged<String> onTapValue;
  final List<DashBoardAddType> dashTypes;
  final bool isSelectMode;

  DashboardAddWidget(
      {Key key, this.onTapValue, this.dashTypes, this.isSelectMode})
      : super(key: key);

  void _onDefaultHandle(BuildContext context, String key) async {
    var result;
    switch (key) {
      case 'quotation':
        result = await Routes.navigateTo(RouterGenProviders.newQuotationPage,
            params: {
              'isSelectMode': isSelectMode,
            });
        break;
      case 'invoice':
        result =
            await Routes.navigateTo(RouterGenProviders.newInvoicePage, params: {
          'isSelectMode': isSelectMode,
        });
        break;
      case 'expense':
        result =
            await Routes.navigateTo(RouterGenProviders.newExpensePage, params: {
          'isSelectMode': isSelectMode,
        });
        break;
      case 'purchase-order':
        result = await Routes.navigateTo(
            RouterGenProviders.newPurchaseOrderPage,
            params: {
              'isSelectMode': isSelectMode,
            });
        break;
      case 'bill':
        result =
            await Routes.navigateTo(RouterGenProviders.newBillPage, params: {
          'isSelectMode': isSelectMode,
        });
        break;
      case 'money-out':
        result =
            await Routes.navigateTo(RouterGenProviders.newCashOutPage, params: {
          'isSelectMode': isSelectMode,
        });
        break;
      case 'make-payment':
        result =
            await Routes.navigateTo(RouterGenProviders.newCashOutPage, params: {
          'isSelectMode': isSelectMode,
          'billList': <BillEntity>[],
        });
        break;
      case 'money-in':
        result =
            await Routes.navigateTo(RouterGenProviders.newCashInPage, params: {
          'isSelectMode': isSelectMode,
        });
        break;
      case 'receive-payment':
        result =
            await Routes.navigateTo(RouterGenProviders.newCashInPage, params: {
          'isSelectMode': isSelectMode,
          'invoiceList': <InvoiceEntity>[],
        });
        break;

      case 'credit-note':
        result = await Routes.navigateTo(RouterGenProviders.newCreditNotePage,
            params: {
              'isSelectMode': isSelectMode,
            });
        break;
      case 'debit-note':
        result = await Routes.navigateTo(RouterGenProviders.newDebitNotePage,
            params: {
              'isSelectMode': isSelectMode,
            });
        break;
      case 'account-transfer':
        result = await Routes.navigateTo(
            RouterGenProviders.newAccountTransferPage,
            params: {
              'isSelectMode': isSelectMode,
            });
        break;
      case 'generate-payslip':
        result = await Routes.navigateTo(
            RouterGenProviders.employeeBatchSelectPage,
            params: {
              'pageTitle': S.current.generate_payslip,
            });
        break;
      case 'record-cpf':
        result = await Routes.navigateTo(
          RouterGenProviders.recordCpfContributionPage,
        );
        break;
    }
    if (result != null) {
      Navigator.of(context).pop();
    }
  }

  List get salesRelated => [
        if (Config.hasPermission(PermissionUtils.quotation))
          {
            'title': S.current.quotation,
            'key': 'quotation',
            'color': aceGreenColor.withOpacity(0.05),
            'asset': A.assetsImagesDashboardAddQuotation,
          },
        if (Config.hasPermission(PermissionUtils.invoice))
          {
            'title': S.current.invoice,
            'key': 'invoice',
            'color': aceGreenColor.withOpacity(0.05),
            'asset': A.assetsImagesDashboardAddInvoice,
          },
        if (Config.hasPermission(PermissionUtils.cashBank))
          {
            'title': S.current.receive__payment,
            'key': 'receive-payment',
            'color': aceGreenColor.withOpacity(0.05),
            'asset': A.assetsImagesDashboardAddCashIn,
          },
      ];

  List get salesSummary => [
        if (Config.hasPermission(PermissionUtils.quotation))
          {
            'title': S.current.quotation,
            'key': 'quotation',
            'color': aceGreenColor.withOpacity(0.05),
            'asset': A.assetsImagesDashboardAddQuotation,
          },
        if (Config.hasPermission(PermissionUtils.invoice))
          {
            'title': S.current.invoice,
            'key': 'invoice',
            'color': aceGreenColor.withOpacity(0.05),
            'asset': A.assetsImagesDashboardAddInvoice,
          },
        if (Config.hasPermission(PermissionUtils.cashBank))
          {
            'title': S.current.receive__payment,
            'key': 'receive-payment',
            'color': aceGreenColor.withOpacity(0.05),
            'asset': A.assetsImagesDashboardAddCashIn,
          },
      ];

  List get purchaseRelated => [
        if (Config.hasPermission(PermissionUtils.purchaseOrder))
          {
            'title': S.current.purchase__order,
            'key': 'purchase-order',
            'color': aceRedColor.withOpacity(0.05),
            'asset': A.assetsImagesDashboardAddPurchase,
          },
        if (Config.hasPermission(PermissionUtils.bill))
          {
            'title': S.current.bill,
            'key': 'bill',
            'color': aceRedColor.withOpacity(0.05),
            'asset': A.assetsImagesDashboardAddBill,
          },
        if (Config.hasPermission(PermissionUtils.cashBank))
          {
            'title': S.current.make__payment,
            'key': 'make-payment',
            'color': aceRedColor.withOpacity(0.05),
            'asset': A.assetsImagesDashboardAddCashOut,
          },
      ];

  List get purchaseSummary => [
        if (Config.hasPermission(PermissionUtils.purchaseOrder))
          {
            'title': S.current.purchase__order,
            'key': 'purchase-order',
            'color': aceRedColor.withOpacity(0.05),
            'asset': A.assetsImagesDashboardAddPurchase,
          },
        if (Config.hasPermission(PermissionUtils.bill))
          {
            'title': S.current.bill,
            'key': 'bill',
            'color': aceRedColor.withOpacity(0.05),
            'asset': A.assetsImagesDashboardAddBill,
          },
        if (Config.hasPermission(PermissionUtils.cashBank))
          {
            'title': S.current.make__payment,
            'key': 'make-payment',
            'color': aceRedColor.withOpacity(0.05),
            'asset': A.assetsImagesDashboardAddCashOut,
          },
      ];

  List get others => [
        if (Config.hasPermission(PermissionUtils.expense))
          {
            'title': S.current.expense,
            'key': 'expense',
            'color': aceDarkGrayColor.withOpacity(0.05),
            'asset': A.assetsImagesDashboardExpense,
          },
        if (Config.hasPermission(PermissionUtils.cashBank))
          {
            'title': S.current.money_in,
            'key': 'money-in',
            'color': aceGreenColor.withOpacity(0.05),
            'asset': A.assetsImagesDashboardAddCashIn,
          },
        if (Config.hasPermission(PermissionUtils.cashBank))
          {
            'title': S.current.money_out,
            'key': 'money-out',
            'color': aceRedColor.withOpacity(0.05),
            'asset': A.assetsImagesDashboardAddCashOut,
          },
      ];

  List get accountTransaction => [
        {
          'title': S.current.money_out,
          'key': 'money-out',
          'color': aceRedColor.withOpacity(0.05),
          'asset': A.assetsImagesDashboardAddCashOut,
        },
        {
          'title': S.current.money_in,
          'key': 'money-in',
          'color': aceGreenColor.withOpacity(0.05),
          'asset': A.assetsImagesDashboardAddCashIn,
        },
        {
          'title': S.current.account_transfer,
          'key': 'account-transfer',
          'color': aceDarkGrayColor.withOpacity(0.05),
          'asset': A.assetsImagesStyleAccountTransfer,
        },
      ];

  List get expenseOrBill => [
        if (Config.hasPermission(PermissionUtils.expense))
          {
            'title': S.current.expense,
            'key': 'expense',
            'color': aceDarkGrayColor.withOpacity(0.05),
            'asset': A.assetsImagesDashboardExpense,
          },
        if (Config.hasPermission(PermissionUtils.bill))
          {
            'title': S.current.bill,
            'key': 'bill',
            'color': aceRedColor.withOpacity(0.05),
            'asset': A.assetsImagesDashboardAddBill,
          },
      ];

  List get payroll => [
        {
          'title': S.current.generate_payslip,
          'key': 'generate-payslip',
          'color': aceDarkGrayColor.withOpacity(0.05),
          'asset': A.assetsImagesDashboardAddInvoice,
        },
        {
          'title': S.current.record_cpf_contribution,
          'key': 'record-cpf',
          'color': aceRedColor.withOpacity(0.05),
          'asset': A.assetsImagesDashboardAddBill,
        },
      ];

  @override
  Widget build(BuildContext context) {
    List<Widget> children = [];
    if (dashTypes.contains(DashBoardAddType.sales) && salesRelated.length > 0) {
      children.addAll([
        _buildListTitle(
          title: S.current.sales_related,
        ),
        GridView(
          padding: EdgeInsets.zero,
          shrinkWrap: true,
          gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
              crossAxisCount: 3, mainAxisExtent: 120),
          children: salesRelated
              .map((e) => _buildListItems(
                    context,
                    title: e['title'],
                    key: e['key'],
                    backgroundColor: e['color'],
                    asset: e['asset'],
                    onTapValue: onTapValue,
                  ))
              .toList(),
        ),
        // Row(
        //   crossAxisAlignment: CrossAxisAlignment.start,
        //   mainAxisAlignment: MainAxisAlignment.start,
        //   children: salesRelated
        //       .map((e) => _buildListItems(
        //             context,
        //             title: e['title'],
        //             key: e['key'],
        //             backgroundColor: e['color'],
        //             asset: e['asset'],
        //             onTapValue: onTapValue,
        //           ))
        //       .toList(),
        // )
      ]);
    }
    if (dashTypes.contains(DashBoardAddType.purchase) &&
        purchaseRelated.length > 0) {
      children.addAll([
        _buildListTitle(
          title: S.current.purchase_related,
        ),
        GridView(
          padding: EdgeInsets.zero,
          shrinkWrap: true,
          gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
              crossAxisCount: 3, mainAxisExtent: 120),
          children: purchaseRelated
              .map((e) => _buildListItems(
                    context,
                    title: e['title'],
                    key: e['key'],
                    backgroundColor: e['color'],
                    asset: e['asset'],
                    onTapValue: onTapValue,
                  ))
              .toList(),
        )
      ]);
    }

    if (dashTypes.contains(DashBoardAddType.other) && others.length > 0) {
      children.addAll([
        _buildListTitle(
          title: S.current.others,
        ),
        GridView(
          padding: EdgeInsets.zero,
          shrinkWrap: true,
          gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
              crossAxisCount: 3, mainAxisExtent: 120),
          children: others
              .map((e) => _buildListItems(
                    context,
                    title: e['title'],
                    key: e['key'],
                    backgroundColor: e['color'],
                    asset: e['asset'],
                    onTapValue: onTapValue,
                  ))
              .toList(),
        )
      ]);
    }
    if (dashTypes.length == 1 &&
        dashTypes.first == DashBoardAddType.accountTransaction) {
      children.addAll([
        Row(
          crossAxisAlignment: CrossAxisAlignment.start,
          mainAxisAlignment: MainAxisAlignment.spaceEvenly,
          children: accountTransaction
              .map((e) => _buildListItems(
                    context,
                    title: e['title'],
                    key: e['key'],
                    backgroundColor: e['color'],
                    asset: e['asset'],
                    onTapValue: onTapValue,
                  ))
              .toList(),
        )
      ]);
    }
    if (dashTypes.length == 1 &&
        dashTypes.first == DashBoardAddType.ExpanseOrBill &&
        expenseOrBill.length > 0) {
      children.addAll([
        Row(
          crossAxisAlignment: CrossAxisAlignment.start,
          mainAxisAlignment: MainAxisAlignment.spaceEvenly,
          children: expenseOrBill
              .map((e) => _buildListItems(
                    context,
                    title: e['title'],
                    key: e['key'],
                    backgroundColor: e['color'],
                    asset: e['asset'],
                    onTapValue: onTapValue,
                  ))
              .toList(),
        )
      ]);
    }
    if (dashTypes.length == 1 &&
        dashTypes.first == DashBoardAddType.purchaseSummary &&
        purchaseSummary.length > 0) {
      children.addAll([
        Row(
          crossAxisAlignment: CrossAxisAlignment.start,
          mainAxisAlignment: MainAxisAlignment.spaceEvenly,
          children: purchaseSummary
              .map((e) => _buildListItems(
                    context,
                    title: e['title'],
                    key: e['key'],
                    backgroundColor: e['color'],
                    asset: e['asset'],
                    onTapValue: onTapValue,
                  ))
              .toList(),
        ),
      ]);
    }
    if (dashTypes.length == 1 &&
        dashTypes.first == DashBoardAddType.saleSummary &&
        salesSummary.length > 0) {
      children.addAll([
        Row(
          crossAxisAlignment: CrossAxisAlignment.start,
          mainAxisAlignment: MainAxisAlignment.spaceEvenly,
          children: salesSummary
              .map((e) => _buildListItems(
                    context,
                    title: e['title'],
                    key: e['key'],
                    backgroundColor: e['color'],
                    asset: e['asset'],
                    onTapValue: onTapValue,
                  ))
              .toList(),
        ),
      ]);
    }
    if (dashTypes.length == 1 && dashTypes.first == DashBoardAddType.payroll) {
      children.addAll([
        Row(
          crossAxisAlignment: CrossAxisAlignment.start,
          mainAxisAlignment: MainAxisAlignment.spaceEvenly,
          children: payroll
              .map((e) => _buildListItems(
                    context,
                    title: e['title'],
                    key: e['key'],
                    backgroundColor: e['color'],
                    asset: e['asset'],
                    onTapValue: onTapValue,
                  ))
              .toList(),
        ),
      ]);
    }
    return ListView(
      shrinkWrap: true,
      padding: EdgeInsets.zero,
      children: [
        ...children,
      ],
    );
  }

  _buildListTitle({String title, Widget rightWidget}) => Padding(
      padding: EdgeInsets.symmetric(
        horizontal: getDp(33),
        vertical: getDp(15),
      ),
      child: Row(
        mainAxisAlignment: MainAxisAlignment.spaceBetween,
        crossAxisAlignment: CrossAxisAlignment.end,
        children: [
          Text(
            title,
            style: TextStyle(
              color: aceBlackColor,
              fontSize: getSp(14),
              fontWeight: FontWeight.w700,
              height: 22 / 14,
            ),
          ),
          if (rightWidget != null) rightWidget,
        ],
      ));

  Widget _buildListItems(BuildContext context,
      {String title,
      String key,
      Color backgroundColor,
      String asset,
      ValueChanged<String> onTapValue}) {
    return PressedOpacityButton(
      onPressed: () {
        if (onTapValue == null) {
          _onDefaultHandle(context, key);
        } else {}
        onTapValue?.call(key);
      },
      child: Column(
        children: [
          Container(
            constraints: BoxConstraints(
              minWidth: getDp(80),
            ),
            padding: EdgeInsets.symmetric(
                horizontal: getDp(21), vertical: getDp(19)),
            decoration: BoxDecoration(
              color: backgroundColor,
              borderRadius: BorderRadius.circular(getDp(10)),
            ),
            child: SvgPicture.asset(
              asset,
              width: getDp(23),
              height: getDp(28),
              fit: BoxFit.contain,
            ),
          ),
          SizedBox(
            height: getDp(8),
          ),
          Text(
            title,
            style: TextStyle(
              color: aceBlackColor,
              fontSize: getSp(14),
              fontWeight: FontWeight.w400,
              height: 22 / 14,
            ),
            textAlign: TextAlign.center,
          ),
        ],
      ),
    );
  }
}
